package com.moyu.shopapp.utils;

import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;


public class JwtUtils {
    private static final String SECRET = "your-secret-key";
    private static final long EXPIRATION = 86400000; // 过期时间（以毫秒为单位）

    /**
     * 生成JWT
     */
    public static String generateJwt(String username) {
        Date now = new Date();
        Date expiration = new Date(now.getTime() + EXPIRATION);
        return Jwts.builder()
                .setSubject(username)
                .setExpiration(expiration)
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
    }

    /**
     *  解析JWT
     *  @return
     */
    public static String parseJwt(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();

        return claims.getSubject();
    }

    /**
     * 判断JWT是否过期
     *
     * @return true(过期)，false(未过期)
     */
    public static boolean isJwtExpired(String token) {
       try{
           Claims claims = Jwts.parser()
                   .setSigningKey(SECRET)
                   .parseClaimsJws(token)
                   .getBody();

           Date expiration = claims.getExpiration();
           return expiration.before(new Date());
       }catch (ExpiredJwtException e){
           return true;
       }
    }
}
